/*
 * This file is part of Cadmium.
 * Copyright (C) 2007-2010 Xavier Clerc.
 *
 * Cadmium is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Cadmium is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package fr.x9c.cadmium.primitives.unix;

import fr.x9c.cadmium.kernel.CodeRunner;
import fr.x9c.cadmium.kernel.Context;
import fr.x9c.cadmium.kernel.Primitive;
import fr.x9c.cadmium.kernel.PrimitiveProvider;
import fr.x9c.cadmium.kernel.Value;
import fr.x9c.cadmium.util.Misc;
import fr.x9c.cadmium.util.Signal;

/**
 * This class provides implementation for 'unix_alarm' primitive.
 *
 * @author <a href="mailto:cadmium@x9c.fr">Xavier Clerc</a>
 * @version 1.0
 * @since 1.0
 */
@PrimitiveProvider
public final class Alarm {

    /** Slot for alarm thread. */
    private static final Object ALARM_SLOT = new Object();

    /**
     * No instance of this class.
     */
    private Alarm() {
    } // end empty constructor

    /**
     * Sets an alarm, sending an alarm signal after a given time.
     * @param ctxt context
     * @param n time in seconds
     * @return the amount of time left on the timer from the previous call to
     *         this primitive or 0 if no alarm is currently set
     */
    @Primitive
    public static Value unix_alarm(final CodeRunner ctxt,
                                   final Value n) {
        final long millisecs = Misc.signedToUnsigned(n.asLong()) * 1000L;
        final Context c = ctxt.getContext();
        final Unix.AlarmThread old = (Unix.AlarmThread) c.getSlot(Alarm.ALARM_SLOT);
        final int res;
        if (old != null) {
            res = (int) (old.unactivate() / ((long) Unix.MILLISECS_PER_SEC));
        } else {
            res = 0;
        } // end if/else
        if (millisecs != 0) {
            c.registerSlot(Alarm.ALARM_SLOT,
                           new Unix.AlarmThread(ctxt,
                                                millisecs,
                                                0,
                                                Signal.Kind.ALRM));
        } // end if
        return Value.createFromLong(res);
    } // end method 'unix_alarm(CodeRunner, Value)'

} // end class 'Alarm'
